import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-08-12
 * Time: 21:44
 */
// 这个类用来实现登录时的校验.
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 防止后端程序不清楚前端的req的编码格式，显示声明
        req.setCharacterEncoding("utf8");
        // 读取form表单提交的数据（从req的body里面读）
        String userName = req.getParameter("username");
        String passWord = req.getParameter("password");
        System.out.println(userName);

        if (userName == null || passWord == null || userName.equals("") || passWord.equals("")) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前输入的用户名或密码不能为空!");
            return;
        }

        if (!userName.equals("李华") && !userName.equals("王五")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户名错误！");
            return;
        }
        if (!passWord.equals("123456")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前密码错误！");
            return;
        }
        HttpSession session = req.getSession(true);

        session.setAttribute("username",userName);

        resp.sendRedirect("index");
    }
}
